package cn.hy.prac.controller.banner;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hy.prac.service.banner.Banner;
import cn.hy.prac.service.banner.BannerService;
import sun.misc.BASE64Decoder;

@Controller
public class BannerController {
	
	@Resource
	private BannerService bannerService;
	
	 @Autowired
     private JmsMessagingTemplate jmsMessagingTemplate;//使用JmsMessagingTemplate将消息放入队列

	@RequestMapping("/")
	public String index(Model model){
		
		List<Banner> bannerList = bannerService.getBannerList();
		model.addAttribute("bannerList", bannerList);
		
		//测试发送activemq消息
		jmsMessagingTemplate.convertAndSend(new ActiveMQQueue("bannerListSize"), bannerList.isEmpty()?"0":bannerList.size());
		
		return "/jsps/index.jsp";
	}
	
	
	/**
	 * 功能描述：拍照并上传图片
	 *
	 * @since 2016/5/24
	 */
	@RequestMapping(value = "/uploadPhoto")
	@ResponseBody
	public void uploadPhoto(HttpServletRequest req, HttpServletResponse resp){
	    //默认传入的参数带类型等参数：data:image/png;base64,
	    String imgStr = req.getParameter("image");
	    if (null != imgStr) {
	        imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
	    }
	    Boolean flag = GenerateImage(imgStr, "", "");
	    String result = "";
	    
	    return ;
	}
	 
	/**
	 * 功能描述：base64字符串转换成图片
	 *
	 * @since 2016/5/24
	 */
	public boolean GenerateImage(String imgStr, String filePath, String fileName) {
	    try {
	        if (imgStr == null) {
	            return false;
	        }
	        BASE64Decoder decoder = new BASE64Decoder();
	        //Base64解码
	        byte[] b = decoder.decodeBuffer(imgStr);
	        //如果目录不存在，则创建
	        File file = new File(filePath);
	        if (!file.exists()) {
	            file.mkdirs();
	        }
	        //生成图片
	        OutputStream out = new FileOutputStream(filePath + fileName);
	        out.write(b);
	        out.flush();
	        out.close();
	        return true;
	    } catch (Exception e) {
	        return false;
	    }
	}
}
